<template>
  <a-card :bordered="false">

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary">新增</a-button>
<!--      <a-button type="primary" icon="download" @click="handleExportXls('分类字典')">导出</a-button>-->
<!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader"  :action="importExcelUrl" @change="handleImportExcel">-->
<!--        <a-button type="primary" icon="import">导入</a-button>-->
<!--      </a-upload>-->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
<!--      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">-->
<!--        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项-->
<!--        <a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
<!--      </div>-->

      <a-table
              ref="table"
              size="middle"
              rowKey="typeCode"
              :columns="columns"
              :scroll="{y:pageHeight-180}"
              :dataSource="dataSource"
              :pagination="false"
              :loading="loading"
              :customRow="onClickRow"
              :expandedRowKeys="expandedRowKeys"
              @change="handleTableChange"
              @expand="handleExpand"
              v-bind="tableProps">

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record)">
            <a>删除</a>
          </a-popconfirm>
          <a-divider type="vertical" />
          <a @click="handleAddSub(record)">添加下级</a>
        </span>

      </a-table>
    </div>

    <category-modal ref="modalForm" @ok="modalFormOk"></category-modal>
  </a-card>
</template>

<script>

  import { getAction,getJSON,postAction } from '@/api/manage'
  import { PageListMixin } from '@/mixins/PageListMixin'
  import categoryModal from './modules/CategoryModal'
  import { deleteAction } from '@/api/manage'

  export default {
    name: "CategoryList",
    mixins:[PageListMixin],
    components: {
      categoryModal
    },
    data () {
      return {
        description: '分类字典管理页面',
        // 表头
        columns: [
          {
            title:'分类名称',
            align:"left",
            dataIndex: 'typeName'
          },
          {
            title:'分类编号',
            align:"left",
            dataIndex: 'typeCode'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          list:  window._CONFIG['domianURL'] + "/goodsclassify/cnGoodsClassify/getProductTypeTree",
          childList:  window._CONFIG['domianURL'] + "/goodsclassify/cnGoodsClassify/getProductTypeTree",
          delete:  window._CONFIG['domianURL'] + "/cnProductTypeController/deleteByid",
          deleteBatch: window._CONFIG['domianURL'] + '/cnProductTypeController/deleteBatch',

        },
        expandedRowKeys:[],
        hasChildrenField:"hasChild",
        pidField:"parentCode",
        dictOptions:{
        },
        subExpandedKeys:[],
      }
    },
    computed: {
      importExcelUrl(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
      tableProps() {
        let _this = this
        return {
          // 列表项是否可选择
          rowSelection: {
            selectedRowKeys: _this.selectedRowKeys,
            onChange: (selectedRowKeys) => _this.selectedRowKeys = selectedRowKeys
          }
        }
      }
    },
    methods: {
      loadData(arg){
        if(arg==1){
          this.ipagination.current=1
        }
        this.loading = true
        this.expandedRowKeys = []
        let params = this.getQueryParams()
        return new Promise((resolve) => {
          postAction(this.url.list,params).then(res=>{
            if(res.success){
              this.dataSource = this.getDataByResult(res.result)

            }else{
              this.$message.warning(res.message)
            }
            this.loading = false
          })
        })
      },
      getDataByResult(result){
        return result.map(item=>{
          //判断是否标记了带有子节点
          if(item[this.hasChildrenField]=='1'){
            let loadChild = { typeCode: item.typeCode+'_loadChild', typeName: 'loading...', isLoading: true }
            item.children = [loadChild]
          }
          return item
        })
      },
      handleExpand(expanded, record){
        // 判断是否是展开状态
        if (expanded) {
          this.expandedRowKeys.push(record.typeCode)
          if (record.children.length>0 && record.children[0].isLoading === true) {
            let params = this.getQueryParams();//查询条件
            params[this.pidField] = record.typeCode
            postAction(this.url.childList,params).then((res)=>{
              if(res.success){
                if(res.result && res.result.length>0){
                  record.children = this.getDataByResult(res.result)
                  this.dataSource = [...this.dataSource]
                }else{
                  record.children=''
                  record.hasChildrenField='0'
                }
              }else{
                this.$message.warning(res.message)
              }
            })
          }
        }else{
          let keyIndex = this.expandedRowKeys.indexOf(record.typeCode)
          if(keyIndex>=0){
            this.expandedRowKeys.splice(keyIndex, 1);
          }
        }
      },
      initDictConfig(){
      },
      editOk(formData,arr){
        if(arr && arr.length>0){
          for(let i=0;i<arr.length;i++){
            if(arr[i].typeCode==formData.typeCode){
              arr[i]=formData
              break
            }else{
              this.editOk(formData,arr[i].children)
            }
          }
        }
      },
      async addOk(formData,arr){
        if(!formData[this.pidField]){
          this.loadData()
        }else{
          this.expandedRowKeys=[]
          console.log("22222",arr)
          for(let i of arr){
            await this.expandTreeNode(i)
          }
        }
      },
      expandTreeNode(nodeId){
        return new Promise((resolve,reject)=>{
          this.getFormDataById(nodeId,this.dataSource)
          let row = this.parentFormData
          this.expandedRowKeys.push(nodeId)
          let params = this.getQueryParams();//查询条件
          params[this.pidField] = nodeId
          getAction(this.url.childList,params).then((res)=>{
            console.log("11111",res)
            if(res.success){
              if(res.result && res.result.length>0){
                row.children = this.getDataByResult(res.result)
                this.dataSource = [...this.dataSource]
                resolve()
              }else{
                row.children=''
                row.hasChildrenField='0'
                reject()
              }
            }else{
              reject()
            }
          })
        })
      },
      getFormDataById(typeCode,arr){
        if(arr && arr.length>0){
          for(let i=0;i<arr.length;i++){
            if(arr[i].typeCode==typeCode){
              this.parentFormData = arr[i]
            }else{
              this.getFormDataById(typeCode,arr[i].children)
            }
          }
        }
      },
      handleAddSub(record){
        this.subExpandedKeys = [];
        this.getExpandKeysByPid(record.typeCode,this.dataSource,this.dataSource)
        this.$refs.modalForm.subExpandedKeys = this.subExpandedKeys;
        this.$refs.modalForm.title = "添加子分类";
        this.$refs.modalForm.disable = true;
        this.$refs.modalForm.edit({'parentCode':record.typeCode,querType:1});
        this.$refs.modalForm.disableSubmit = false;
      },
      handleDelete: function (record) {
        let that = this;
        that.loading = true
        deleteAction(that.url.delete, {id: record.id}).then((res) => {
          if (res.success) {
            if (record.parentCode && record.parentCode!='0') {
              let formData = {parentCode: record.parentCode};
              that.$message.success(res.message);
              that.subExpandedKeys = [];
              that.getExpandKeysByPid(record.parentCode, this.dataSource, this.dataSource)
              that.addOk(formData, this.subExpandedKeys.reverse())
              that.loadData();
              that.loading = false
            } else {
              that.loadData();
            }
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      // 添加子分类时获取所有父级id
      getExpandKeysByPid(parentCode,arr,all){
        if(parentCode && arr && arr.length>0){
          for(let i=0;i<arr.length;i++){
            if(arr[i].typeCode==parentCode){
              this.subExpandedKeys.push(arr[i].typeCode)
              this.getExpandKeysByPid(arr[i]['parentCode'],all,all)
            }else{
              this.getExpandKeysByPid(parentCode,arr[i].children,all)
            }
          }
        }
      },


    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>
